package com.example.chapter13;


import java.io.*;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;

/*
* 13.2.2.文件系统
* */
public class Demo02 {

    public static void main(String[] args) {

        //在项目path/to/your目录下创建file.txt文件
        File file = new File("path/to/your/file.txt");
        if (file.exists()) {
            System.out.println("File exists.");
        } else {
            System.out.println("File does not exist.");
        }

        //Java使用输入流（InputStream和Reader）来读取数据，使用输出流（OutputStream和Writer）来写入数据
        try (FileInputStream fis = new FileInputStream(file);
             BufferedInputStream bis = new BufferedInputStream(fis)) {
            byte[] buffer = new byte[1024];
            int bytesRead;
            while ((bytesRead = bis.read(buffer)) != -1) {
                // 处理读取到的数据
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

        //写入文件
        try (FileOutputStream fos = new FileOutputStream(file);
             BufferedOutputStream bos = new BufferedOutputStream(fos)) {
            String data = "Some data to write.";
            bos.write(data.getBytes());
        } catch (IOException e) {
            e.printStackTrace();
        }


        //Path 和 Paths
        Path path = Paths.get("path/to/your/file.txt");
        //Files 类读取文件
        try {
            List<String> lines = Files.readAllLines(path);
            // 处理读取到的行数据
        } catch (IOException e) {
            e.printStackTrace();
        }
        //写入文件
        String data = "Some data to write.";
        try {
            Files.write(path, data.getBytes());
        } catch (IOException e) {
            e.printStackTrace();
        }

        //创建目录
        Path dir = Paths.get("path/to/your/directory");
        try {
            Files.createDirectories(dir);
        } catch (IOException e) {
            e.printStackTrace();
        }

        //删除文件或目录
        try {
            Files.delete(path);
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}
